package com.tmpt.service.impl;

import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import com.tmpt.beans.A2Job;
import com.tmpt.dao.intf.IA2JobDao;
import com.tmpt.dao.intf.ITemplateDao;
import com.tmpt.dto.Result;
import com.tmpt.service.IQuartzService;
import com.tmpt.utils.DateTool;
import org.apache.log4j.Logger;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.googlecode.genericdao.search.Search;
import com.quartz2.jobs.BeanObjectJobAction;
import com.quartz2.jobs.ProcedureJobAction;
import com.quartz2.manager.AutoJobDTO;
import com.quartz2.manager.JobManager;

@Service
@Transactional(propagation = Propagation.REQUIRED)
public class QuartzService implements IQuartzService {

	private Logger log = Logger.getLogger(this.getClass());

	@Resource private IA2JobDao jobDao;
	@Resource private JobManager jobManager;
    @Resource private IQuartzService quartzService;
	@Resource private TemplateServiceUtils templateServiceUtils;
	private String dataSource = "dsA";
	
	

	@Override
	public Result timerStartup(long a2Job_id){
		Result result = new Result();
		//取job
		A2Job job = jobDao.fetch(a2Job_id);
		jobDao.refresh(job);//执行时间通过jdbc修改数据库的，缓存要更新下
		int mode = job.getMode();
		String jobName = job.getJobName();
		String jobDes = job.getJobDes();
		String jobClass = job.getJobClass();
		String beanMethod = job.getBeanMethod();
		String expression = job.getExpression();
		String param = job.getParam();
		
		//加入工作任务
        try {
            AutoJobDTO jobDto = new AutoJobDTO();  
            //执行job类
        	if(mode == 0){
                jobDto.setJob_id(""+job.getId());  
                jobDto.setJob_name(job.getJobName());  
                jobDto.setJob_group(AutoJobDTO._JOB_Group);  
                jobDto.setJob_time(job.getExpression());  
            	jobManager.addJob(jobDto, Class.forName(jobClass));
        	}
        	//bean object 
        	if(mode == 1){
                jobDto.setJob_id(""+job.getId());  
                jobDto.setJob_name(job.getJobName());  
                jobDto.setJob_group(AutoJobDTO._JOB_Group);  
                jobDto.setJob_time(job.getExpression());  
                jobDto.setBeanObject(job.getJobClass());
                jobDto.setBeanMethod(job.getBeanMethod());
            	jobManager.addJob(jobDto, BeanObjectJobAction.class);
        	}
        	//存储过程
        	if(mode == 2){
                jobDto.setJob_id(""+job.getId());  
                jobDto.setJob_name(job.getJobName());  
                jobDto.setJob_group(AutoJobDTO._JOB_Group);  
                jobDto.setJob_time(job.getExpression());  
                jobDto.setProcedure(job.getJobClass());
            	jobManager.addJob(jobDto, ProcedureJobAction.class);
        	}
        	
    		//startJobs
            jobManager.startJobs();  
            //.out.println("------------定时器启动成功："+job.getJobName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return result.fault("job class 加入失败！ClassNotFoundException"+e.getLocalizedMessage());
		} catch (SchedulerException e) {
			e.printStackTrace();
			return result.fault("job class 加入失败 ！SchedulerException"+e.getLocalizedMessage());
		}  catch (Exception e) {
			e.printStackTrace();
			return result.fault("job class 加入失败 ！Exception"+e.getLocalizedMessage());
		}
		
        job.setIsActivity(1);
        jobDao.update(job);
		
		return result.success();
	}
	
	
	@Override
	public Result timerShutdown(long a2Job_id) {
		Result result = new Result();
		//取job
		A2Job job = jobDao.fetch(a2Job_id);
		jobDao.refresh(job);//执行时间通过jdbc修改数据库的，缓存要更新下
		String jobName = job.getJobName();
		String jobDes = job.getJobDes();
		String jobClass = job.getJobClass();
		String expression = job.getExpression();
		String param = job.getParam();

		//Remove Job
        AutoJobDTO jobDto = new AutoJobDTO();  
        jobDto.setJob_id(""+job.getId());  
        jobDto.setJob_name(job.getJobName());  
        jobDto.setJob_group(AutoJobDTO._JOB_Group);  
        jobDto.setJob_time(job.getExpression());  
    	jobManager.removeJob(jobDto);

        job.setIsActivity(0);
        jobDao.update(job);
        //.out.println("------------定时器关闭成功："+job.getJobName());
        
		return result.success();
	}
	

	@Override
	public Result timerRestart(long a2Job_id) {
		Result result = new Result();
		
		//shutdown
		result = quartzService.timerShutdown(a2Job_id);
		if(!result.isSuccess()){
			return result;
		}
		//startup
		result = quartzService.timerStartup(a2Job_id);
		
		return result;
	}
	

	/**
	 * 服务重启时，自动启动所有任务
	 */
	@Override
	public Result startAllJob(){
		Result result = new Result();
		Search search = new Search();
		search.addFilterEqual("deleteFlag", "0");
		search.addFilterEqual("isActivity", "1");
		List<A2Job> jobList = jobDao.search(search);
		for(A2Job job: jobList){
			long jobId = job.getId();
			result = timerStartup(jobId);
			if(!result.isSuccess()){
				throw new RuntimeException("定时器启动失败："+result.getContent());
			}
		}
		
		return result.success();
	}
	
	
	/**
	 * 配置定时执行存储过程
	 * @param paramMap
	 * @return
	 */
	public Result executeProcedureJob(String procedure, Map<String,Object> paramMap){
		Result result = new Result();

		ITemplateDao templateDao = templateServiceUtils.getTemplateDao(this.dataSource);
		result = templateDao.executeProcedureJob(procedure, paramMap);
		
		return result;
	}
	
	/**
	 * spring bean 调用测试
	 */
	@Override
	public Result testQuartz(Map<String,Object> paramMap){
		Result result = new Result();
		System.out.println("----------paramMap size:"+paramMap.keySet().size());

		System.out.println("------------testQuartz:"+ DateTool.getCurrentDateStr1("yyyy-MM-dd HH:mm:ss.SSS"));
		
		return result.success();
	}
	

	
	
}
